package com.cloudweb.oa.controller;

import cn.js.fan.db.ListResult;
import cn.js.fan.util.ParamUtil;
import cn.js.fan.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.cloudweb.oa.vo.Result;
import com.redmoon.oa.flow.WorkflowSequenceDb;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Vector;

@RestController
@RequestMapping("/flow/sequence")
public class WorkflowSequenceController {

    @Autowired
    HttpServletRequest request;

    @ApiOperation(value = "自动编号列表", notes = "自动编号列表", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页数量", required = true, dataType = "Integer"),
    })
    @ApiResponses({ @ApiResponse(code = 200, message = "操作成功") })
    @ResponseBody
    @RequestMapping(value = "/list", method = RequestMethod.POST, produces = {"text/html;charset=UTF-8;", "application/json;charset=UTF-8;"})
    public Result<Object> list(@RequestParam(value="page", defaultValue = "1") Integer page, @RequestParam(value="pageSize", defaultValue = "20") Integer pageSize) {
        String op = ParamUtil.get(request, "op");
        String by = ParamUtil.get(request, "by");
        String what = ParamUtil.get(request, "what");

        WorkflowSequenceDb wf = new WorkflowSequenceDb();

        String sql = "select id from flow_sequence order by name asc";
        if ("search".equals(op)) {
            if ("name".equals(by)) {
                sql = "select id from flow_sequence where name like " + StrUtil.sqlstr("%" + what + "%") + " order by name asc";
            }
        }

        ListResult lr = wf.listResult(sql, page, pageSize);
        com.alibaba.fastjson.JSONArray rows = new com.alibaba.fastjson.JSONArray();
        JSONObject jobject = new JSONObject();
        jobject.put("list", rows);
        jobject.put("page", page);
        jobject.put("total", lr.getTotal());

        Vector v = lr.getResult();
        for (Object o : v) {
            WorkflowSequenceDb wsd = (WorkflowSequenceDb) o;
            JSONObject json = new JSONObject();
            json.put("id", wsd.getId());
            json.put("name", wsd.getName());
            json.put("typeDesc", wsd.getType() == WorkflowSequenceDb.TYPE_NUMBER ? "数值型" : "组合型");
            json.put("curValue", wsd.getType() == WorkflowSequenceDb.TYPE_COMPOUND ? wsd.getCurValue() : wsd.getCurIndex());
            json.put("template", wsd.getTemplate());
            json.put("length", wsd.getLength());
            rows.add(json);
        }
        return new Result<>(jobject);
    }

    @ApiOperation(value = "删除", notes = "删除", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "ID以逗号分隔", required = true, dataType = "String"),
    })
    @ApiResponses({ @ApiResponse(code = 200, message = "操作成功") })
    @PreAuthorize("hasAnyAuthority('admin')")
    @ResponseBody
    @RequestMapping(value = "/del", method = RequestMethod.POST, produces = {"text/html;charset=UTF-8;", "application/json;charset=UTF-8;"})
    public Result<Object> del(@RequestParam(value = "ids") String ids) {
        boolean re = false;
        String[] ary = StrUtil.split(ids, ",");
        for (String s : ary) {
            int id = StrUtil.toInt(s);
            WorkflowSequenceDb wsd = new WorkflowSequenceDb();
            wsd = wsd.getWorkflowSequenceDb(id);
            re = wsd.del();
        }
        return new Result<>(re);
    }

    @ApiOperation(value = "创建", notes = "创建", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "序列名称", required = true, dataType = "String"),
    })
    @ApiResponses({ @ApiResponse(code = 200, message = "操作成功") })
    @PreAuthorize("hasAnyAuthority('admin')")
    @ResponseBody
    @RequestMapping(value = "/create", method = RequestMethod.POST, produces = {"text/html;charset=UTF-8;", "application/json;charset=UTF-8;"})
    public Result<Object> create(@RequestParam(value = "name") String name) {
        long beginIndex = ParamUtil.getLong(request, "beginIndex");
        String curIndex = ParamUtil.get(request, "curIndex").trim();
        String curValue = ParamUtil.get(request, "curValue").trim();
        String len = ParamUtil.get(request, "length").trim();
        String template = ParamUtil.get(request, "template").trim();
        if (template.length() > 45) {
            return new Result<>(false, "规则过长，不能大于45");
        }

        //判断“当前值”是否与“规则”匹配
        if ("{num}".equals(template)) {//数值型
            //判断“当前值”是否为数字
            if (!curIndex.matches("[0-9]+")) {
                return new Result<>(false, "“当前值”必须是数字");
            }
        } else {//组合型
            curIndex = "0";
        }
        //判断“补齐位数”是否为数字
        if (!len.matches("[0-9]+")) {
            return new Result<>(false, "“补齐位数”必须是数字");
        }

        String itemSeparator = ParamUtil.get(request, "itemSeparator");
        int yearDigit = ParamUtil.getInt(request, "yearDigit", 4);

        WorkflowSequenceDb wsd = new WorkflowSequenceDb();
        wsd.setBeginIndex(beginIndex);
        wsd.setCurIndex(Long.parseLong(curIndex));
        wsd.setCurValue(curValue);
        wsd.setLength(Integer.parseInt(len));
        wsd.setName(name);
        wsd.setTemplate(template);

        wsd.setItemSeparator(itemSeparator);
        wsd.setYearDigit(yearDigit);

        if ("{num}".equals(template.trim()) || "{num:year}".equals(template.trim()) || "{num:month}".equals(template.trim()) || "{num:day}".equals(template.trim())) {
            wsd.setType(WorkflowSequenceDb.TYPE_NUMBER);
        } else {
            wsd.setType(WorkflowSequenceDb.TYPE_COMPOUND);
        }
        return new Result<>(wsd.create());
    }

    @ApiOperation(value = "修改页面", notes = "修改页面", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "Integer"),
    })
    @ApiResponses({ @ApiResponse(code = 200, message = "操作成功") })
    @PreAuthorize("hasAnyAuthority('admin')")
    @ResponseBody
    @RequestMapping(value = "/editPage", method = RequestMethod.POST, produces = {"text/html;charset=UTF-8;", "application/json;charset=UTF-8;"})
    public Result<Object> editPage(@RequestParam(value = "id") Integer id) {
        String template = "{num}";
        int seq_type = 0;
        String[] strs = new String[4];
        WorkflowSequenceDb wsd = new WorkflowSequenceDb(id);
        template = wsd.getTemplate();
        seq_type = wsd.getType();

        //修改时如果是组合型，需要将“规则”状态记录。并根据此状态在“规则设置”中选定不同的按钮
        if(seq_type == 1){  //表示是组合型
            String str = template;
            int index = str.lastIndexOf("{");
            String preString = str.substring(0, index);
            String nextString = str.substring(index);
            int index2 = preString.lastIndexOf("{");
            if(index2 == -1){
                index2 = 0;
            }
            String preString2 = preString.substring(0, index2);
            strs[3] = nextString;//因为最后一个"{"肯定是{num}这一组
            String[] strArr = preString.split("\\{");//在从前半部分截取处理
            String last = strArr[strArr.length-1];//得到数组最后一位，看符合哪一组
            String lastPreOne = "";
            String lastPreTwo = "";
            if(strArr.length == 2){
                lastPreOne = strArr[strArr.length-2];
            }else if(strArr.length > 2){
                lastPreOne = strArr[strArr.length-2];
                lastPreTwo = strArr[strArr.length-3];
            }
            if("date:yyyy}-".equals(last)){
                strs[2] = "{date:yyyy}";
                if("dept}-".equals(lastPreOne)){
                    strs[1] = "{dept}";
                    if(preString2.lastIndexOf("{") == -1){
                        strs[0] = preString2;
                    }else{
                        strs[0] = preString2.substring(0, preString2.lastIndexOf("{"));
                    }
                }else{
                    strs[1] = "";
                    if(preString.lastIndexOf("{") == -1){
                        strs[0] = preString;
                    }else{
                        strs[0] = preString.substring(0, preString.lastIndexOf("{"));
                    }
                }
            }else if("date:yyyy-MM}-".equals(last)){
                strs[2] = "{date:yyyy-MM}";
                if("dept}-".equals(lastPreOne)){
                    strs[1] = "{dept}";
                    if(preString2.lastIndexOf("{") == -1){
                        strs[0] = preString2;
                    }else{
                        strs[0] = preString2.substring(0, preString2.lastIndexOf("{"));
                    }
                }else{
                    strs[1] = "";
                    if(preString.lastIndexOf("{") == -1){
                        strs[0] = preString;
                    }else{
                        strs[0] = preString.substring(0, preString.lastIndexOf("{"));
                    }
                }
            }else if("date:yyyy-MM-dd}-".equals(last)){
                strs[2] = "{date:yyyy-MM-dd}";
                if("dept}-".equals(lastPreOne)){
                    strs[1] = "{dept}";
                    if(preString2.lastIndexOf("{") == -1){
                        strs[0] = preString2;
                    }else{
                        strs[0] = preString2.substring(0, preString2.lastIndexOf("{"));
                    }
                }else{
                    strs[1] = "";
                    if(preString.lastIndexOf("{") == -1){
                        strs[0] = preString;
                    }else{
                        strs[0] = preString.substring(0, preString.lastIndexOf("{"));
                    }
                }
            }else if("dept}-".equals(last)){
                strs[2] = "";
                strs[1] = "{dept}";
                if(preString2.lastIndexOf("{") == -1){
                    strs[0] = preString2;
                }else{
                    strs[0] = preString2.substring(0, preString2.lastIndexOf("{"));
                }

            }else{
                strs[2] = "";
                strs[1] = "";
                strs[0] = preString;
            }
        }

        JSONObject json = new JSONObject();
        json.put("id", wsd.getId());
        json.put("name", wsd.getName());
        json.put("typeDesc", wsd.getType() == WorkflowSequenceDb.TYPE_NUMBER ? "数值型" : "组合型");
        json.put("curValue", wsd.getCurValue());
        json.put("curIndex", wsd.getCurIndex());
        json.put("template", wsd.getTemplate());
        json.put("length", wsd.getLength());
        json.put("prefixValue", strs[0] == null ? "" : strs[0]);
        json.put("itemSeparator", wsd.getItemSeparator());
        json.put("yearDigit", wsd.getYearDigit());
        json.put("beginIndex", wsd.getBeginIndex());

        boolean dept = false;
        if(seq_type == 1){
            if(!"".equals(strs[1]) && strs[1]!=null) {
                dept = true;
            }
        }
        json.put("dept", dept);

        String yearNum = "";
        if (!"".equals(strs[2]) && strs[2] != null) {
            yearNum = strs[2];
        }
        json.put("yearNum", yearNum);

        String yearNumReset = "";
        if (!"".equals(strs[3]) && strs[3] != null) {
            yearNumReset = strs[3];
        }
        json.put("yearNumReset", yearNumReset);
        return new Result<>(json);
    }

    @ApiOperation(value = "修改", notes = "修改", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "Integer"),
    })
    @ApiResponses({ @ApiResponse(code = 200, message = "操作成功") })
    @PreAuthorize("hasAnyAuthority('admin')")
    @ResponseBody
    @RequestMapping(value = "/update", method = RequestMethod.POST, produces = {"text/html;charset=UTF-8;", "application/json;charset=UTF-8;"})
    public Result<Object> update(@RequestParam(value = "id") Integer id) {
        String name = ParamUtil.get(request, "name").trim();
        long beginIndex = ParamUtil.getLong(request, "beginIndex");
        long curIndex = ParamUtil.getLong(request, "curIndex", 0);
        String len = ParamUtil.get(request, "length").trim();
        String template = ParamUtil.get(request, "template");
        String curValue = ParamUtil.get(request, "curValue");
        if (template.length() > 45) {
            return new Result<>(false, "规则过长，不能大于45");
        }

        int type;
        if ("{num}".equals(template.trim()) || "{num:year}".equals(template.trim()) || "{num:month}".equals(template.trim()) || "{num:day}".equals(template.trim())) {
            type = WorkflowSequenceDb.TYPE_NUMBER;
        } else {
            type = WorkflowSequenceDb.TYPE_COMPOUND;
        }

        //判断“当前值”是否与“规则”匹配
        if (type == WorkflowSequenceDb.TYPE_NUMBER) {
            //数值型，判断“当前值”是否为数字
            if (!curValue.matches("[0-9]+")) {
                return new Result<>(false, "当前值 必须是数字");
            }
            curIndex = StrUtil.toLong(curValue);
        } else {
            //组合型
            curIndex = 0;
        }
        //判断“补齐位数”是否为数字
        if (!len.matches("[0-9]+")) {
            return new Result<>(false, "“补齐位数”必须是数字");
        }

        String itemSeparator = ParamUtil.get(request, "itemSeparator");
        int yearDigit = ParamUtil.getInt(request, "yearDigit", 4);

        WorkflowSequenceDb wsd = new WorkflowSequenceDb();
        wsd = wsd.getWorkflowSequenceDb(id);
        wsd.setBeginIndex(beginIndex);
        wsd.setCurIndex(curIndex);
        wsd.setLength(Integer.parseInt(len));
        wsd.setName(name);
        wsd.setTemplate(template);
        wsd.setCurValue(curValue);
        wsd.setItemSeparator(itemSeparator);
        wsd.setYearDigit(yearDigit);
        wsd.setType(type);

        return new Result<>(wsd.save());
    }
}
